package com.travel.travel_springboot_web.controller;

import com.travel.travel_springboot_web.entity.Goods;
import com.travel.travel_springboot_web.entity.GoodsImage;
import com.travel.travel_springboot_web.service.GoodsService;
import com.travel.travel_springboot_web.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/goods")
@CrossOrigin(methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
public class GoodsController {
    
    private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);
    
    @Autowired
    private FileUtil fileUtil;
    
    @Autowired
    private GoodsService goodsService;
    
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
        logger.info("Receiving upload request for file: {}", file.getOriginalFilename());
        Map<String, Object> result = new HashMap<>();
        try {
            String fileUrl = fileUtil.saveFile(file);
            logger.info("File uploaded successfully. Original name: {}, Saved URL: {}", 
                    file.getOriginalFilename(), fileUrl);
            
            // 直接保存图片信息到数据库
            GoodsImage goodsImage = new GoodsImage();
            goodsImage.setImageUrl(fileUrl);
            goodsImage.setSort(0);
            // 临时设置goods_id为0，表示未关联商品
            goodsImage.setGoodsId(0L);
            goodsService.saveImage(goodsImage);
            
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", new HashMap<String, Object>() {{
                put("url", fileUrl);
                put("fullUrl", "http://localhost:8080" + fileUrl);
            }});
        } catch (Exception e) {
            logger.error("File upload failed: ", e);
            result.put("code", 500);
            result.put("message", "Error: " + e.getMessage());
        }
        return result;
    }
    
    @PostMapping(value = "/uploadMultiple", consumes = "multipart/form-data")
    public Map<String, Object> uploadMultiple(@RequestParam("files") MultipartFile[] files) {
        logger.info("Receiving multiple files upload request");
        Map<String, Object> result = new HashMap<>();
        try {
            List<Map<String, String>> urls = new ArrayList<>();
            for (MultipartFile file : files) {
                String fileUrl = fileUtil.saveFile(file);
                urls.add(new HashMap<String, String>() {{
                    put("url", fileUrl);
                    put("fullUrl", "http://localhost:8080" + fileUrl);
                }});
            }
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", urls);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "Error: " + e.getMessage());
        }
        return result;
    }
    
    @PostMapping(value = "/publish", consumes = "application/json")
    public Map<String, Object> publish(@RequestBody Goods goods) {
        logger.info("Receiving publish request");
        Map<String, Object> result = new HashMap<>();
        try {
            // 打印接收到的原始数据
            logger.info("Received request data: title={}, desc={}, price={}, stock={}, imageUrls={}", 
                    goods.getTitle(), goods.getDesc(), goods.getPrice(), goods.getStock(), goods.getImageUrls());

            // 检查并处理图片URL
            if (goods.getImageUrls() != null && !goods.getImageUrls().isEmpty()) {
                List<String> fullUrls = goods.getImageUrls().stream()
                    .map(url -> {
                        if (!url.startsWith("/") && !url.startsWith("http")) {
                            return "/uploads/" + url;  // 添加路径前缀
                        }
                        return url;
                    })
                    .collect(Collectors.toList());
                goods.setImageUrls(fullUrls);
                logger.info("Processed imageUrls: {}", fullUrls);
            } else {
                logger.warn("No imageUrls in request data");
            }

            Goods savedGoods = goodsService.createGoods(goods);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", savedGoods);
        } catch (Exception e) {
            logger.error("Failed to publish goods: ", e);
            result.put("code", 500);
            result.put("message", "Error: " + e.getMessage());
        }
        return result;
    }
    
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(required = false) String keyword) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("Getting goods list with keyword: {}", keyword);
            List<Goods> goodsList = goodsService.getGoodsList(keyword);
            
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", goodsList);
        } catch (Exception e) {
            logger.error("Failed to get goods list: ", e);
            result.put("code", 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Long id, 
                                    @RequestParam(defaultValue = "true") boolean soft) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("Deleting goods: id={}, soft={}", id, soft);
            
            boolean success = goodsService.deleteGoods(id, soft);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "success");
            } else {
                result.put("code", 404);
                result.put("message", "Goods not found");
            }
        } catch (Exception e) {
            logger.error("Failed to delete goods: ", e);
            result.put("code", 500);
            result.put("message", "Error: " + e.getMessage());
        }
        return result;
    }
    
    @PutMapping("/{id}")
    public Map<String, Object> update(@PathVariable Long id, @RequestBody Goods goods) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("Updating goods: id={}, data={}", id, goods);
            
            // 设置ID
            goods.setId(id);
            
            // 设置默认值
            if (goods.getStatus() == null) {
                goods.setStatus(1);  // 默认状态为1（上架）
            }
            if (goods.getSales() == null) {
                goods.setSales(0);   // 默认销量为0
            }
            
            // 检查并处理图片URL
            if (goods.getImageUrls() != null && !goods.getImageUrls().isEmpty()) {
                List<String> fullUrls = goods.getImageUrls().stream()
                    .map(url -> {
                        if (!url.startsWith("/") && !url.startsWith("http")) {
                            return "/uploads/" + url;  // 添加路径前缀
                        }
                        return url;
                    })
                    .collect(Collectors.toList());
                goods.setImageUrls(fullUrls);
                logger.info("Processed imageUrls: {}", fullUrls);
                
                // 设置主图（使用第一张图片作为主图）
                goods.setCoverImage(goods.getImageUrls().get(0));
                logger.info("Set cover image: {}", goods.getCoverImage());
            }
            
            boolean success = goodsService.updateGoods(goods);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "success");
                result.put("data", goods);
            } else {
                result.put("code", 404);
                result.put("message", "Goods not found");
            }
        } catch (Exception e) {
            logger.error("Failed to update goods: ", e);
            result.put("code", 500);
            result.put("message", "Error: " + e.getMessage());
        }
        return result;
    }
} 